﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;

public class DownLoadManager2 : UnitySingleton<DownLoadManager2>
{

    public override void Init()
    {

    }

    /// <summary>
    /// 检查版本号
    /// </summary>
    public void CheckVersion()
    {
        //对比服务器版本号和本地版本号
        string serverVersionNo = "";
        string localVersionNo = "";
        if(serverVersionNo == localVersionNo)
        {
            //版本号相等，进入登录界面
        }
        else
        {
            //不相等，对比版本详细信息
            List<string> serverVersionInfos = new List<string>();
            List<string> localVersionInfos = new List<string>();
            DownLoad(AppConfig.SERVICE_VERSION_INFO, (wwwServer) =>
            {
                //加载服务器版本信息
                //Debug.Log("version:" + www.text);
                string[] strs = wwwServer.text.Split('\n');
                for (int i = 0; i < strs.Length; i++)
                {
                    if(!string.IsNullOrEmpty(strs[i]))
                    {
                        serverVersionInfos.Add(strs[i]);
                    }
                }

                if (File.Exists(AppConfig.LOCAL_VERSION_INFO))
                {
                    //加载本地版本信息
                    DownLoad(AppConfig.SERVICE_VERSION_INFO, (wwwLocal) =>
                    {
                        strs = wwwLocal.text.Split('\n');
                        for (int i = 0; i < strs.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(strs[i]))
                            {
                                localVersionInfos.Add(strs[i]);
                            }
                        }
                        DownLoadRes(serverVersionInfos, localVersionInfos);
                    });
                }
                else
                {
                    DownLoadRes(serverVersionInfos, localVersionInfos);
                }
            });
        } 
    }

    public void DownLoadRes(List<string> serverVersionInfos, List<string> localVersionInfos)
    {
        for (int i = 0; i < serverVersionInfos.Count; i++)
        {
            if (!localVersionInfos.Contains(serverVersionInfos[i]))
            {
                //该资源没有更新完毕，则下载资源
                DownLoad(AppConfig.SERVER_RES_ADDRESS + serverVersionInfos[i], (www) =>
                {
                    byte[] bytes = www.bytes;
                    CreateFile(bytes, "");
                    //下载完毕，则把更新信息更新到本地版本信息
                    WriteVersionInfo(AppConfig.LOCAL_VERSION_INFO, serverVersionInfos[i]);
                    localVersionInfos.Add(serverVersionInfos[i]);
                });
            }
        }
    }

    public string LoadLocalTxt(string path)
    {
        string str = "";
        //var filePath = Path.Combine(url, fileName);
        FileInfo fileInfo = new FileInfo(path);
        if (fileInfo.Exists)
        {
            StreamReader sr = new StreamReader(path);
            str = sr.ReadToEnd();
        }
        return str;
    }

    public void DownLoad(string path, Action<WWW> callback)
    {
        StartCoroutine(_DownLoad(path, callback));
    }

    private IEnumerator _DownLoad(string path, Action<WWW> callback)
    {
        //path = "file:///" + Application.persistentDataPath + "/Res/Lua_version.txt";
        WWW www = new WWW(path);

        yield return www;

        if (string.IsNullOrEmpty(www.error))
        {
            if (callback != null)
                callback(www);
        }
        else
        {
            Loger.Error("DownLoadManager", path + "Error is :" + www.error);
            if (callback != null)
                callback(null);
        }
    }


    /// <summary>
    /// 下载资源并保存到指定目录
    /// </summary>
    /// <param name="path"></param>
    /// <param name="savePath"></param>
    /// <param name="callback"></param>
    public  void DownLoadToSave(string path, string savePath, Action callback)
    {
        ResManager.Instance.StartCoroutine(_DownLoadToSave(path, savePath, callback));
    }

    private static IEnumerator _DownLoadToSave(string path, string savePath, Action callback)
    {
        WWW www = new WWW(path);

        yield return www;
    }


    /// <summary>
    /// 创建文件
    /// </summary>
    /// <param name="bytes"></param>
    /// <param name="savePath"></param>
    private void CreateFile(byte[] bytes, string savePath)
    {
        string path = Application.persistentDataPath + "/Res";
        string[] strs = savePath.Split('/');
        if (strs.Length > 0)
        {
            string dir = savePath.Substring(0, savePath.Length - strs[strs.Length - 1].Length);
            //dir = path + dir;
            //Debug.Log("dir:" + dir);
            if (!Directory.Exists(dir))
            {
                //如果不存在该目录，则创建该目录
                Debug.Log("dir:" + dir);
                Directory.CreateDirectory(dir);
            }
        }
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        FileInfo fileInfo = new FileInfo(savePath);
        Stream stream = fileInfo.Create();
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        stream.Dispose();
    }


    /// <summary>
    /// 解压文件
    /// </summary>
    private void CreateFileByZip(byte[] bytes, string savePath = null)
    {
        string path = Application.persistentDataPath + "/Res";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        FileInfo fileInfo = new FileInfo(savePath);
        Stream stream = fileInfo.Create();
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        stream.Dispose();
    }


    /// <summary>
    /// 解压到沙河路径
    /// </summary>
    private void UnZip()
    {
        //Loger.Info("UnZip----");
        string savePath = Application.persistentDataPath + "/Res/Res.zip";
        string sourcePath = ApplicationPlatform.GetStreamingAssetsPath();// + "/Res";
        //Debug.Log(savePath);
        //Loger.Info("UnZip----savePath:" + savePath);
        if (Directory.Exists(Application.persistentDataPath + "/Res"))
        {
            IO.DeleteFiles(Application.persistentDataPath + "/Res");
        }
        DownLoadManager.DownLoad(sourcePath + "Res.zip", (www) =>
        {
            byte[] bytes = www.bytes;
            CreateFileByZip(bytes, savePath);
            Debug.Log(savePath);
            //FZipHelper.UnZip(savePath, Application.persistentDataPath + "/Res");
            IO.DeleteFiles(savePath);
            //StartGame();
        });
    }

    /// <summary>
    /// 更新本地版本信息
    /// </summary>
    /// <param name="path"></param>
    /// <param name="info"></param>
    public void WriteVersionInfo(string file,string info)
    {
        using (FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.BaseStream.Seek(0, SeekOrigin.End);
                sw.WriteLine("{0}\n", info);
                sw.Flush();
            }
        }
    }


}
